#滚动
canScroll = on #控制滚动
@scroll = (y,reScrllTime=6000)->
	if on == y or off ==y
		canScroll = y
		if !y and reScrllTime
			reScrllTime *=1000 if reScrllTime<100
			setTimeout ->
				canScroll = on
			,reScrllTime
		return off
	oldY = document.body.scrollTop
	iY = 0
	timer = setInterval( ->
		unless canScroll
			return off
		newY = document.body.scrollTop
		document.body.scrollTop += 1 + Math.ceil(Math.random()*5)
		if newY == document.body.scrollTop
			iY++
		else
			iY=0
		if document.body.scrollTop - oldY > y or iY>1000
			clearInterval timer
	,20)
#定位垂直位置
@scrollTop = (y,relative=off)->
	if relative
		document.body.scrollTop += y
	else
		document.body.scrollTop = y
#截图
#callback 截图后的操作
#callback,timeDelay 截图后的操作,延迟多少时间（单位为秒）再截图
#timeDelay 延迟截图
#beforCallback 在截图前的操作
@capture = (callback,timeDelay=0,beforCallback='')->
	if callback > 0 # 相当于不要第一个参数
		if $.isFunction(timeDelay)
			beforCallback = timeDelay
		timeDelay = callback
	setTimeout ->
		beforCallback() if beforCallback
		chrome.extension.sendRequest capture:1
		console.debug new Date().toLocaleTimeString()
		console.count('capture')
		if $.isFunction(callback)
			setTimeout ->
				callback()
			,500
	,timeDelay*1000

#得到宝贝的id
@getItemId = (url)->
	regex = /[?&]id=(\d+)/ig
	r = regex.exec url
	if r
		return r[1]
	else
		0

#点击其它宝贝
clicked = off #当前面是否已经点击其它宝贝
@clickOther = ()->
	console.debug 'clickOther'
	meId = getItemId(location.href)
	chrome.extension.sendRequest {clickId:meId,clickedIds:1,leftView:1},(response)->
		#打印返回数据
		console.debug 'receive click msg ',new Date().toLocaleTimeString(),response
		if response and response.buy and response.buy.leftView>0
				clickA = (a)->
					id = getItemId a.href
					img = $('img',a)[0]
					if id>0 and id not in response.buy.clickedIds and id != meId and img and a.href.indexOf('item') > -1
						simulateClick img,{ctrl:on}
						clicked = on
						chrome.extension.sendRequest clickId:getItemId(a.href)
						return off
					on
				#遍历查找，去点击
				for selectorStr in ['a[href^="http://ju.mmstat.com"]','a[href^="http://item.taobao.com"]']
					if clicked
						break
					allAs = $(selectorStr).toArray()
					allAs.sort ->
						Math.random() - 0.5
					for a in allAs
						unless clickA a
							break
				if clicked
					console.debug 'clicked'
				else
					console.error 'noClicked'
		else
			console.debug 'no click response'

